package com.example.samchat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {
	private String mAddr;
	ChattingDto dto;
	ArrayList<SamMsg> arData;
	SamMsgAdapter adapter;
	private ProgressDialog mProgress;
	DownThread thread1;
	String a = new String();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		arData = new ArrayList<SamMsg>();
		
		arData.add(new SamMsg("hi", ""));
		arData.add(new SamMsg("", "Hello~"));
		
		adapter = new SamMsgAdapter(this, R.layout.chatmsg,	arData);
		
		ListView list = (ListView)findViewById(R.id.list);
		list.setAdapter(adapter);
		list.setDividerHeight(0);
		
//		mProgress = ProgressDialog.show(this, "Wait", "Downloading...");
		DownThread thread = new DownThread("http://godling2.cafe24.com/chat/index.php/room/msgs/id/1");
		thread.start();
	}
	
	class DownThread extends Thread {
		private String mAddr;

		public DownThread(String addr) {
			mAddr = addr;
		}
		
		public void run() {
			HttpGet get = new HttpGet(mAddr);
			DefaultHttpClient client = new DefaultHttpClient();
			try {
				client.execute(get, mResHandler);
			}
			catch (Exception e) {;}
		}
	}
	
	ResponseHandler<String> mResHandler = new ResponseHandler<String>() {

		@Override
		public String handleResponse(HttpResponse response)
				throws ClientProtocolException, IOException {
			StringBuilder sb = new StringBuilder();
			String html = new String();
			String html1 = new String();
			String num = new String();
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				for (;;) {
					String line = br.readLine();
					if (line == null) break;
					sb.append(line + '\n');
				}
				br.close();
				
				try {
					JSONArray arr = new JSONArray(html);
					for (int i = 0; i < arr.length(); i++) {
						JSONObject obj = arr.getJSONObject(i);
						obj = (JSONObject) obj.get("b");
						html1 = obj.getString("context");
						num = obj.getString("num");

						sb.append(html1 + "\n");
						Log.e("JSONObject Log", html1 + " -\n");
					}
					a = num;
					dto.setNum(num);
					Log.e("22222222222", dto.getNum());

				} catch (Exception e) {
					e.printStackTrace();
				}
				Message message = null;
				message = mAfterDown.obtainMessage();
				message.obj = sb.toString().trim();
				mAfterDown.sendMessage(message);
			} catch (Exception e) {
			}
			return null;
		}
	};
	
	Handler mAfterDown = new Handler() {
		public void handleMessage(Message msg) {
			arData.add(new SamMsg((String)msg.obj, ""));
			adapter.notifyDataSetChanged();
		}
	};
	
	public void mOnClick(View v) {
		EditText ed = (EditText)findViewById(R.id.newmsg);
		switch(v.getId()) {
		case R.id.send:
			String text = ed.getText().toString();
			if (text.length() != 0) {
				arData.add(new SamMsg("", text));
				ed.setText("");
				adapter.notifyDataSetChanged();
				ListView list = (ListView)findViewById(R.id.list);
				list.setSelection(arData.size() - 1);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	class SamMsg {
		String OtherMsg, MyMsg;

		SamMsg(String otherMsg, String myMsg) {
			OtherMsg = otherMsg;
			MyMsg = myMsg;
		}
	}
	
	class SamMsgAdapter extends BaseAdapter {

		private Context context;
		private LayoutInflater Inflater;
		private ArrayList<SamMsg> arSrc;
		private int layout;

		SamMsgAdapter(Context context, int layout, ArrayList<SamMsg> arData){
			this.context = context;
			this.Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.arSrc = arData;
			this.layout = layout;
		}
		
		@Override
		public int getCount() {
			return arSrc.size();
		}

		@Override
		public String getItem(int position) {
			SamMsg msg = arSrc.get(position);
			if (msg.MyMsg.length() != 0)
				return msg.MyMsg;
			
			return msg.OtherMsg;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView,	ViewGroup parent) {
			if (convertView == null) {
				convertView = this.Inflater.inflate(layout, parent, false);
			}
			
			TextView otherText = (TextView)convertView.findViewById(R.id.othermsg);
			otherText.setText(arSrc.get(position).OtherMsg);
			TextView myText = (TextView)convertView.findViewById(R.id.mymsg);
			myText.setText(arSrc.get(position).MyMsg);
			
			return convertView;
		}		
	}
}
